<!--
 * @Author: wangding
 * @Date: 2020-11-09 14:33:19
 * @LastEditTime: 2021-01-04 14:13:27
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \solaxcloud\src\views\device\sn\sn.vue
-->
<template>
    <div class="found-sn-main-box">
        
        <div class="search-box">
            <div class="search-box-sub">
                <span class="lable-text">{{$t('site.siteName')}}</span>
                <el-input v-model="searchData.siteName" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('login.loginName')}}</span>
                <el-input v-model="searchData.loginName" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('Gateway SN')}}</span>
                <el-input v-big v-model="searchData.gateSN" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('Mac_Address')}}</span>
                <el-input v-big v-model="searchData.macAddr" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('device.inverter.enableFlag')}}</span>
                <el-select v-model="searchData.onlineStatus" clearable @change="disabledDevice">
                    <el-option v-for="item in onlineStatusList" :key="item.value" :label="item.name" :value="item.value"></el-option>
                </el-select>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('Operating_Status')}}</span>
                <el-select v-model="searchData.deviceStatus" clearable :disabled="searchData.onlineStatus==='0'">
                    <el-option v-for="item in deviceStatusList" :key="item.value" :label="item.name" :value="item.value"></el-option>
                </el-select>
            </div>
            
            <div class="search-box-sub">
                <el-button type="primary" @click='query'>{{$t('query')}}</el-button>
            </div>
        </div>
        <!-- <div class="button-box">
            <el-button type="primary" @click='addModal'>批量重置密钥</el-button>
            <el-button type="primary" @click='addModal'>批量升级</el-button>
            <el-button type="primary" @click='addModal'>批量禁用</el-button>
        </div> -->
        <baseTable v-loading="loading"  row-key='sid' :data="dataRows" border  stripe   :column='column' :select='false'>
            <template #onlineStatus="{data}">
                <span :style='data.onlineStatus==1?"color:#429dff":""'>
                    <i class="iconfont icon-wifi" style="vertical-align: middle;" ></i>
                    {{comm.returnCode(onlineStatusList,data.onlineStatus,'value','name')}}
                </span>
            </template>
            <template #deviceStatus="{data}">
                <template v-if="data.onlineStatus!=1">
                    -
                </template>
                <template v-if="data.onlineStatus==1">
                    {{comm.returnCode(deviceStatusList,data.deviceStatus,'value','name')}}
                </template>
            </template>
            <template #updateStatus="{data}">
                {{comm.returnCode(updateStatusList,data.updateStatus,'value','name')}}
            </template>
            <template #enableFlag="{data}">
                {{comm.returnCode(enableFlagList,data.enableFlag,'value','name')}}
            </template>
            <template #option="{data}">
                <div class="option-box">
                    <el-button type="text" style='font-size:18px;' icon='el-icon-upload' :title="$t('devWifi.upgrade')" :disabled="data.enableUpdate" @click='updateDevice(data.sid,data.gateVersion)'></el-button>

                    <el-button style='font-size:18px;'  v-if='data.updateFlag == 1&&data.enableFlag == 1' type="" icon='el-icon-refresh-left' :title="$t('reset.button')" @click='wifiEditEntity(data)'></el-button>

                    <el-popconfirm
                        :confirm-button-text="$t('sure')"
                        :cancel-button-text="$t('cancel')"
                        :title="$t('Reset_Key')"
                        @confirm='resetCipher(data.sid)'
                    >
                        <el-button class="marginR10" style='font-size:18px;' slot="reference" icon='iconfont icon-zhongzhimima' :title="$t('Reset_Key')"></el-button>
                    </el-popconfirm>

                    <el-popconfirm
                        :confirm-button-text="$t('sure')"
                        :cancel-button-text="$t('cancel')"
                        :title="$t('Reset_Account')"
                        @confirm='resetAccount(data.sid)'
                    >
                        <el-button class="marginR10" style='font-size:18px;' slot="reference" icon='iconfont icon-editUser' :title="$t('Reset_Account')"></el-button>
                    </el-popconfirm>

                    <el-button class="marginR10" type="" icon='iconfont icon-jinyong' :title="$t('version.versionService.forbidden')" v-if="disabledFlag==1&&data.enableFlag==1" @click='deviceSwitch(data.sid,1)'></el-button>

                    <el-button class="marginR10" type="" icon='iconfont icon-check-circle' :title="$t('Unban')"  style='color:' v-if="disabledFlag==1&&data.enableFlag!=1" @click='deviceSwitch(data.sid,0)'></el-button>
                </div>
            </template>
        </baseTable>
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
        <updateModal :gatewayIds="gatewayIds" :packageList="packageList" @uploadData="initTable" @refreshStatus="refreshStatus"></updateModal>
    </div>
</template>

<script>
import baseTable from '../../../components/common/baseTable'
import updateModal from './edit'
export default {
    components: {
        baseTable,
        updateModal
    },
    props: {

    },
    data() {
        return {
            searchData:{
                siteName:'',
                userName:'',
                gateSN:'',
                macAddr:'',
                onlineStatus:'',
                deviceStatus:'',
            },
            disabledFlag:0,
            gatewayIds:'',
            // onlineStatusList:[{name:'在线',value:'1'},{name:'离线',value:'0'}],
            onlineStatusList:[{name:this.$t('inventoryManage.statusLine'),value:'1'},{name:this.$t('inventoryManage.statusOffline'),value:'0'}],
            deviceStatusList:[{name:this.$t('Active'),value:'1'},{name:this.$t('Inactive'),value:'0'}],
            updateStatusList:[{name:this.$t('Loading'),value:'0'},{name:this.$t('To_be_Upgraded'),value:'1'},{name:this.$t('Upgrading'),value:'2'},{name:this.$t('Upgrade_completed'),value:'3'},,{name:this.$t('Upgrade_failed'),value:'4'}],
            enableFlagList:[{name:this.$t('Disable'),value:'0'},{name:this.$t('Enable'),value:'1'}],
            packageList:[],
            loading:false,
            dataRows:[],
            size:10,
            total:1,
            current:1,
            column:[{
                title: this.$t('user.loginName'),
                value: 'loginName',
            },{
                title: this.$t('site.siteName'),
                value: 'siteName'
            },{
                title: 'Gateway SN',
                value: 'gateSN'
            },{
                title: this.$t('Mac_Address'),
                value: 'macAddr',
            },{
                title: this.$t('version.versionAdd.versionNum'),
                value: 'gateVersion',
            }, {
                title: this.$t('Operating_Status'),
                value: 'deviceStatus',
                slot:'deviceStatus'
            }, {
                title: this.$t('Available_Status'),
                value: 'enableFlag',
                slot:'enableFlag',
            },{
                title: this.$t('Number_of_connected_device'),
                value: 'deviceNum',
            },{
                title: this.$t('battery.accessTime'),
                value: 'accessTime',
            },{
                title: this.$t('device.inverter.enableFlag'),
                value: 'onlineStatus',
                slot:'onlineStatus'
            },{
                title: this.$t('devUpgrade.upgradeStatus'),
                value: 'updateStatus',
                slot: 'updateStatus',
            },{
                title: this.$t('control'),
                slot: 'option',
            }],
            timeOutId:null,
            updateIds:[]
        };
    },
    computed: {
        newVisibleEdit(){
            return this.$store.state.sysStore.newVisibleEdit
        }
    },
    watch: {

    },
    created() {

    },
    beforeDestroy(){
        //页面销毁前清除计时器
        window.clearTimeout(this.timeOutId)
    },
    mounted() {
        this.devgatewayShowSwitchButton()
        this.initTable()
    },
    methods: {
        //离线时禁用工作状态
        disabledDevice(val){
            console.log(val)
            if(val==='0'){
                this.searchData.deviceStatus=''
            }
        },
        //获取是否有禁用按钮权限
        async devgatewayShowSwitchButton(){
            let res=await this.API.devgatewayShowSwitchButton()
            this.disabledFlag=res
            console.log(res,'res222')
        },
        //禁用
        async deviceSwitch(id,state){
            let res = await this.API.devgatewayDeviceSwitch({
                gatewayIds:id,
                state:state
            })
            if(res.success){
                this.$message.success(this.$t('index.control_success'))
            }else{
                this.$message.error(this.$t('index.control_fail'))
            }
            this.initTable()
        },
        //Reset_Key
        async resetCipher(id){
            let res = await this.API.devgatewayResetCipher({
                gatewayIds:id
            })
            if(res.success){
                this.$message.success(this.$t('index.control_success'))
            }else{
                this.$message.error(this.$t('index.control_fail'))
            }
            this.initTable()
        },
        //Reset_Account
        async resetAccount(id){
            let res = await this.API.devgatewayHomeassistant({
                gatewayIds:id
            })
            if(res.success){
                this.$message.success(this.$t('index.control_success'))
            }else{
                this.$message.error(this.$t('index.control_fail'))
            }
            this.initTable()
        },
        //升级
        async updateDevice(id,gateVersion){
            let res = await this.API.devgatewayupdategetList()
            console.log(res,'res-----------------')
            res.forEach((item,i)=>{
                console.log(i)
                console.log(gateVersion)
                if(item.fullVersion==gateVersion){
                    res.splice(i,1)
                    console.log(i)
                    return false
                }
            })
            console.log(res)
            this.packageList=res
            this.gatewayIds=id
            this.$store.commit('setNewVisibleEdit',true)
        },
        async initTable(){
            this.loading = true
            let res = await this.API.devgatewayGetPage({
                size:this.size,
                current:this.current,
                ...this.searchData
            })
            this.total = res.total
            this.dataRows = res.rows
            this.loading = false
        },
        async refreshStatus(gatewayIds){
            console.log(this.updateIds,'updateIds前')
            if(gatewayIds){
                if( !this.updateIds.includes( gatewayIds ) ){//includes 检测数组是否有某个值
                    this.updateIds.push(gatewayIds);
                }
            }

            console.log(this.updateIds,'updateIds后')
            if(this.updateIds.length>0){
                let res = await this.API.devgatewayGetUpdateStatus({
                    gatewayIds:this.updateIds.join()
                })
                console.log(res,'定时获取状态')
                
                res.forEach(item => {
                    console.log(item.updateStatus)
                    this.dataRows.forEach((row,i) =>{
                        if(row.sid == item.sid){
                            this.$set(row,'updateStatus',item.updateStatus)
                            this.$set(row,'enableUpdate',true)
                            console.log(item.gateVersion,'item.gateVersion')
                            console.log(row.gateVersion,'row.gateVersion')
                            if(
                                (item.updateStatus==3 && item.gateVersion!=row.gateVersion)||//升级完成
                                item.updateStatus==4 //升级失败
                            ){
                                this.updateIds.forEach((id,i)=>{
                                    if(id==item.sid){
                                        this.$set(row,'enableUpdate',false)
                                        this.updateIds.splice(i,1)
                                    }
                                })
                                
                            }
                            this.$set(row,'gateVersion',item.gateVersion)
                        }
                    })
                });
                if(this.updateIds.length>0){
                    window.clearTimeout(this.timeOutId)
                    this.timeOutId=window.setTimeout(()=>{
                        this.refreshStatus()
                    },5*1000)
                }else{
                    console.log('升级完成-内')
                    window.clearTimeout(this.timeOutId)
                }
            }else{
                console.log('升级完成-外')
                window.clearTimeout(this.timeOutId)
            }
        },
        query(){
            this.current = 1
            this.initTable()
        },
        handleCurrentChange(val) {
          this.current = val
          this.initTable()
        },
        handleSizeChange(val) {
          this.size = val
          this.current = 1
          this.initTable()
        },
    },
};
</script>

<style  lang="less" scoped>

</style>
